package com.zeng.es_jd.util;

import com.zeng.es_jd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {
    // 爬取数据
    public List<Content> parseJD(String keywords) throws Exception {
        String url = "https://search.jd.com/Search?keyword="+keywords;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();

        for (Element el : elements) {
            // 这种网站，一般为了保证效率，一般会延时加载图片
            // String img = el.getElementsByTag("img").eq(0).attr("src");
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
            goodsList.add(content);
        }
        return goodsList;
    }

//    public static void main(String[] args) throws Exception {
//        new HtmlParseUtil().parseJD("vue").forEach(System.out::println);
//        String url = "https://search.jd.com/Search?keyword=java";
//        Document document = Jsoup.parse(new URL(url), 30000);
//
//        Element element = document.getElementById("J_goodsList");
//
//        Elements elements = element.getElementsByTag("li");
//
//        for (Element el : elements) {
//            // 这种网站，一般为了保证效率，一般会延时加载图片
//            // String img = el.getElementsByTag("img").eq(0).attr("src");
//            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
//            String price = el.getElementsByClass("p-price").eq(0).text();
//            String title = el.getElementsByClass("p-name").eq(0).text();
//
//            System.out.println(img);
//            System.out.println(price);
//            System.out.println(title);
//            System.out.println("=========================================");
//        }
//    }
}
